//
//  StatusPictureView.swift
//  Weibo
//
//  Created by 周先生 on 15/11/15.
//  Copyright © 2015年 周先生. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
private let PictureCellId = "PictureCellId"
private let PictureCellMargin: CGFloat = 5
class StatusPictureView: UICollectionView {
    
    var imageUrls: [NSURL]? {
        didSet {
        
            //刷新数据
            reloadData()
        
            let viewSize = self.cacleViewSize()
            //注意这边是更新约束
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
            }
            testLabel.text = "\(imageUrls?.count ?? 0)"
        }
    
    }
    
    //计算配图视图大小
    private func cacleViewSize() -> CGSize {
    
        //获取配图最大宽度
        let colum: CGFloat = 3.00000000000001
        let maxWidth: CGFloat = screenW - 2 * StatusCellMargin
        //单个图片宽度
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //设置cell的大小
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        let imageCount = imageUrls?.count ?? 0
        //无图
        if imageCount == 0 {
            
            return CGSizeZero
        }
        //单张图片
        if imageCount == 1 {
            //后续再处理单张图片
            //获取单张被缓存的文件
            let key = imageUrls?.last?.absoluteString
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            let imageSize = image.size
//            let imageSize = CGSize(width: 180, height: 120)
            layout.itemSize = imageSize
            return imageSize
        }
        //四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            return CGSize(width: w, height: w)
        }
        
        //多图
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = row * itemWidth + (row - 1) * PictureCellMargin
        return CGSize(width: w, height: h)
    }
    //3,调用设置UI的方法  重写父类的构造方法调用设置UI
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置layout
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册cell 
        registerClass(PictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        //设置数据源 自己成为自己的数据源
        dataSource = self
        setupUI()
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //2,设置UI
    private func setupUI() {
    
        backgroundColor = UIColor.randomColor()
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    
    }
    //1,懒加载子控件
    private lazy var testLabel: UILabel = {
        let l = UILabel()
        l.font = UIFont.systemFontOfSize(25)
        l.textColor = UIColor.blueColor()
        l.sizeToFit()
        return l
    }()
    

}

/**
*  实现必选的数据源方法
*/
extension StatusPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageUrls?.count ?? 0
        
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! PictureCell
//        cell.backgroundColor = UIColor.randomColor()
        cell.url = imageUrls![indexPath.item]
        return cell
    }

}

class PictureCell: UICollectionViewCell {

    
    //
    var url: NSURL? {
    
        didSet {
        imageView.sd_setImageWithURL(url, placeholderImage: nil)
        
        }
    
    }

    //3,重写父类的构造方法 调用设置UI方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //2,设置UI
    private func setupUI() {
    
        //添加子控件
        contentView.addSubview(imageView)
        //设置约束
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    
    }
    //1,懒加载所有的子控件
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        //设置图片样式
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        //手写代码 必须手动添加剪裁
        iv.clipsToBounds = true
    return iv
    
    }()
}







